import json 
import datetime
import hashlib

from flask import Blueprint
from flask import request
from flask import Response


from sqlalchemy import create_engine, text, Column, Integer, String, Sequence
from flask_sqlalchemy import SQLAlchemy

from app.comm.db import db
from app.system import auth
from app.comm.db import jsonformater
from app.comm.pub import RestEntity
from app.comm.pub import class2dict

userservice = Blueprint('user', __name__, )


class User(db.Model):
    __tablename__ = 'sys_user'
    user_id = Column(Integer, primary_key=True)
    user_name = Column(String(80), unique=True, nullable=False)    
    dept_id= Column(String(80), unique=True, nullable=False)
    login_name= Column(String(80), unique=True, nullable=False)
    password= Column(String(80), unique=True, nullable=False)     
    user_type= Column(String(80), unique=True, nullable=False)
    email= Column(String(80), unique=True, nullable=False)
    phonenumber= Column(String(80), unique=True, nullable=False)
    qqtoken= Column(String(80), unique=True, nullable=False)
    weixintoken= Column(String(80), unique=True, nullable=False)
    weibotoken= Column(String(80), unique=True, nullable=False)
    sex= Column(String(80), unique=True, nullable=False)
    avatar= Column(String(80), unique=True, nullable=False)
    salt= Column(String(80), unique=True, nullable=False)
    status= Column(String(80), unique=True, nullable=False)
    del_flag= Column(String(80), unique=True, nullable=False)
    login_ip= Column(String(80), unique=True, nullable=False)
    login_date= Column(String(80), unique=True, nullable=False)
    create_by= Column(String(80), unique=True, nullable=False)
    create_time= Column(String(80), unique=True, nullable=False)
    update_by= Column(String(80), unique=True, nullable=False)
    update_time= Column(String(80), unique=True, nullable=False)
    remark= Column(String(80), unique=True, nullable=False)

    def as_dict(self):
        return {c.name: str(getattr(self, c.name)) for c in self.__table__.columns}

    def __repr__(self):
        return '<User %r>' % self.username


@userservice.route("/rest/system/user/login", methods=['POST', 'GET'])
def userLogin():
    print(request.get_data().decode('utf-8'))
    logindata = json.loads(request.get_data().decode('utf-8'))
    h = hashlib.sha256()
    # 2.填充要加密的数据
    password = logindata["password"]
    h.update(bytes(password, encoding='utf-8'))
    # 3.获取加密结果
    passwordnew = h.hexdigest() 
    logindata["password"]=passwordnew

    sqlfilter="user_name='"+logindata["loginname"]+"' and password='"+logindata["password"]+"'"

    tmpuser = User.query.filter(text(sqlfilter)).first().as_dict()
    # dict1["email"]=tmpuser.email
    print(tmpuser)
    # 获取token
    if tmpuser==None :
        result = RestEntity(-1, 0, "{}", "登陆失败！！", "")
    else :        
        token = auth.encode_auth_token(logindata["loginname"], 10).decode()
        #返回登录信息
        userinfo={"loginname":logindata["loginname"]}
        #
        result = RestEntity(0, 0, userinfo, "登陆成功！", token)
        # print(json.dumps(class2dict(result)))
    return json.dumps(class2dict(result))

#使用微信登录
@userservice.route("/rest/system/user/loginByWeiXin", methods=['POST', 'GET'])
def userLoginByWeiXin():
    print(request.get_data().decode('utf-8'))
    logindata = json.loads(request.get_data().decode('utf-8'))
  

    sqlfilter="weixintoken='"+logindata["weixingtoken"]+"'"

    tmpuser = User.query.filter(text(sqlfilter)).first().as_dict()
    # dict1["email"]=tmpuser.email
    print(tmpuser)
    # 获取token
    if tmpuser==None :
        #添加到数据库
        sql = "insert into sys_user (login_name,user_name,weixintoken) values(:loginname,:username,:weixintoken)"
 
        # dict1 = json.loads(a)
        dataresult = db.session.execute(sql,logindata)
        db.session.commit()
        result = RestEntity(-1, 0, "{}", "登陆失败！！", "")
    else :        
        token = auth.encode_auth_token(logindata["loginname"], 10).decode()
        #返回登录信息
        userinfo={"loginname":logindata["loginname"]}
        #
        result = RestEntity(0, 0, userinfo, "登陆成功！", token)
        # print(json.dumps(class2dict(result)))
    return json.dumps(class2dict(result))

@userservice.route("/rest/system/user/reg", methods=['POST', 'GET'])
def userReg():
    print(request.get_data().decode('utf-8'))
    regdata = json.loads(request.get_data().decode('utf-8'))
    #密码做混淆
    h = hashlib.sha256()
    # 2.填充要加密的数据
    password = regdata["password"]
    h.update(bytes(password, encoding='utf-8'))
    # 3.获取加密结果
    passwordnew = h.hexdigest() 
    regdata["password"]=passwordnew
    regdata["username"]=regdata["loginname"]
    #
    sql = "insert into sys_user (login_name,user_name,password,email) values(:loginname,:username,:password,:email)"
 
    # dict1 = json.loads(a)
    dataresult = db.session.execute(sql,regdata)
    db.session.commit()
     
    result = RestEntity(-1, 0,dataresult, "注册成功！")
    return json.dumps(class2dict(result), default=jsonformater)

# return json.dumps(dict1)
@userservice.route("/rest/system/user/list", methods=['POST', 'GET'])
def userList():
    a = request.get_data()

    # dict1 = json.loads(a)
    tables = db.session.execute(
        "select user_id userId,dept_id deptId,login_name loginName,user_name userName,user_type userType,email,phonenumber,sex,avatar,status,remark,create_time createTime from sys_user").fetchall()
    datas = [dict(r) for r in tables]
    result = RestEntity(0, 0, datas, "登陆成功！")
    return json.dumps(class2dict(result), default=jsonformater)

    # return json.dumps(dict1)


@userservice.route("/rest/system/user/edit", methods=['POST', 'GET'])
def userEdit():
    editdata = request.get_data()
    print(editdata)
    tmpuser = User.query.filter_by(user_name='管理员').first().as_dict()
    # dict1["email"]=tmpuser.email
    print(tmpuser)

    result = RestEntity(0, 0, tmpuser, "登陆成功！")
    return json.dumps(class2dict(result))

    # return json.dumps(dict1)


@userservice.route("/rest/system/user/remove", methods=['POST', 'GET'])
def userRemove():
    print(request.values)
    ids = request.values.get('ids')
    sql = "update  sys_user set del_flag=2 where user_id=" + ids
    print(sql)
    # dict1 = json.loads(a)
    intcount = db.session.execute(sql)
    db.session.commit()
    # datas= [dict(r) for r in tables]
    result = RestEntity(0, 0, intcount, "登陆成功！")
    return json.dumps(class2dict(result), default=jsonformater)


@userservice.route("/rest/system/user/checkPhoneUnique", methods=['POST', 'GET'])
def checkPhoneUnique():
    # print(request.values)
    userId = request.values.get('userId')
    phonenumber = request.values.get('phonenumber')

    sql = "select count(*) from   sys_user where phonenumber=" + phonenumber + " and user_id<>'" + userId + "'"

    # dict1 = json.loads(a)
    datacount = db.session.execute(sql).first()
    print(datacount)

    # datas= [dict(r) for r in tables]
    result = RestEntity(-1, 0, datacount[0], "登陆成功！")
    return json.dumps(class2dict(result), default=jsonformater)

    # return json.dumps(dict1)
'''
检查用户的名称是否唯一
'''
@userservice.route("/rest/system/user/checkLoginNameUnique", methods=['POST', 'GET'])
def checkLoginNameUnique():
    # print(request.values)
    loginName = request.values.get('loginname')

    sql = "select count(*) from   sys_user where logi_name= %(loginname)s"
    #sql = “INSERT INTO user VALUES(%(username)s, %(password)s, %(email)s)”
    value = {"loginname":loginName} 

    # dict1 = json.loads(a)
    datacount = db.session.execute(sql,value).first()
    print(datacount)

    # datas= [dict(r) for r in tables]
    result = RestEntity(-1, 0, datacount[0], "登录名监测！")
    return json.dumps(class2dict(result), default=jsonformater)


@userservice.route("/rest/system/user/checkEmailUnique", methods=['POST', 'GET'])
def checkEmailUnique():
    # print(request.values)
    userId = request.values.get('userId')
    email = request.values.get('email')

    sql = "select count(*) from   sys_user where email='" + email + "' and user_id<>'" + userId + "'"

    # dict1 = json.loads(a)
    intcount = db.session.execute(sql).first()
    print(intcount)

    # datas= [dict(r) for r in tables]
    result = RestEntity(-1, 0, intcount[0], "登陆成功！")
    return json.dumps(class2dict(result), default=jsonformater)

    # return json.dumps(dict1)
